package com.qmscy.sparrow.config;

import com.qmscy.sparrow.common.filter.JWTAuthenticationFilter;
import com.qmscy.sparrow.common.filter.JWTLoginFilter;
import com.qmscy.sparrow.component.MD5PasswordEncoder;
import com.qmscy.sparrow.config.properties.JwtProperties;
import com.qmscy.sparrow.service.UserService;
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security configuration <br>
 *
 * @Author: wangxiaonan
 * @Date: 2018/12/28
 **/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserService userService;
    @Resource
    private MD5PasswordEncoder md5PasswordEncoder;
    @Resource
    private JwtProperties jwtProperties;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/druid/**").permitAll()
//                .antMatchers("/hello").authenticated()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTLoginFilter(authenticationManager(), jwtProperties))
                .addFilterBefore(new JWTAuthenticationFilter(authenticationManager(), jwtProperties),
                        UsernamePasswordAuthenticationFilter.class)
                .logout() // 默认注销行为为logout，可以通过下面的方式来修改
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login");// 设置注销成功后跳转页面，默认是跳转到登录页面;
        // 禁用缓存
        http.headers().cacheControl();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(md5PasswordEncoder);
    }

}
